<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI选股系统 - 批量导入</title>
    <script src="/static/lib/js/vue.global.js"></script>
    <script src="/static/lib/js/axios.min.js"></script>
    <link href="/static/lib/css/all.min.css" rel="stylesheet">
    <link href="/static/base.css" rel="stylesheet">
    <link href="/static/components.css" rel="stylesheet">
    <link href="/static/pages.css" rel="stylesheet">
    <link href="/static/utilities.css" rel="stylesheet">
    <link href="/static/optimized-table-styles.css" rel="stylesheet">
    <link href="/static/admin/admin.css" rel="stylesheet">
    <style>
        .batch-import-container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .import-options {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .import-card {
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            padding: 24px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .import-card:hover {
            border-color: #007bff;
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.15);
        }
        
        .import-card.active {
            border-color: #007bff;
            background: #f0f8ff;
        }
        
        .import-card.disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .import-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }
        
        .import-card.hsnapshot .import-icon {
            color: #1976d2;
        }
        
        .import-card.fboard .import-icon {
            color: #7b1fa2;
        }
        
        .import-title {
            font-size: 1.2em;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .import-description {
            color: #666;
            margin-bottom: 16px;
        }
        
        .file-count {
            background: #f8f9fa;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 0.9em;
            color: #495057;
            margin-bottom: 16px;
        }
        
        .import-button {
            width: 100%;
            padding: 12px;
            font-size: 1.1em;
            font-weight: 500;
        }
        
        .progress-container {
            margin-top: 30px;
            background: white;
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        
        .progress-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .progress-title {
            font-size: 1.2em;
            font-weight: 600;
        }
        
        .progress-status {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.9em;
            font-weight: 500;
        }
        
        .progress-status.importing {
            background: #fff3cd;
            color: #856404;
        }
        
        .progress-status.completed {
            background: #d4edda;
            color: #155724;
        }
        
        .progress-status.error {
            background: #f8d7da;
            color: #721c24;
        }
        
        .progress-bar {
            width: 100%;
            height: 12px;
            background: #e0e0e0;
            border-radius: 6px;
            overflow: hidden;
            margin-bottom: 16px;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #007bff, #0056b3);
            transition: width 0.3s ease;
        }
        
        .progress-details {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .current-file {
            font-weight: 500;
            color: #495057;
        }
        
        .progress-text {
            color: #666;
            font-size: 0.9em;
        }
        
        .import-results {
            margin-top: 20px;
        }
        
        .result-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .result-item:last-child {
            border-bottom: none;
        }
        
        .result-file {
            flex: 1;
            font-weight: 500;
        }
        
        .result-status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8em;
            font-weight: 500;
            margin-left: 12px;
        }
        
        .result-status.success {
            background: #d4edda;
            color: #155724;
        }
        
        .result-status.error {
            background: #f8d7da;
            color: #721c24;
        }
        
        .result-status.warning {
            background: #fff3cd;
            color: #856404;
        }
        
        .summary-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 16px;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
        }
        
        .stat-item {
            text-align: center;
            padding: 16px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .stat-value {
            font-size: 1.5em;
            font-weight: 600;
            margin-bottom: 4px;
        }
        
        .stat-label {
            color: #666;
            font-size: 0.9em;
        }
        
        .stat-success .stat-value {
            color: #28a745;
        }
        
        .stat-error .stat-value {
            color: #dc3545;
        }
        
        .stat-warning .stat-value {
            color: #ffc107;
        }
        
        .stat-total .stat-value {
            color: #007bff;
        }
    </style>
</head>
<body>
  <div id="app" class="admin-layout">
    <!-- 顶部导航 -->
    <div class="admin-header">
      <h2>批量导入</h2>
      <div>
        <button class="btn" onclick="location.href='/'">返回前台</button>
        <button class="btn" onclick="logout()">退出</button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="admin-main">
      <!-- 左侧导航（公共组件注入） -->
      <div class="admin-sidebar"></div>

      <!-- 右侧内容区域 -->
      <div class="admin-content">
        <div class="content-page active">
          <h3>批量导入</h3>
          <p class="page-description">从数据目录批量导入股票快照和涨停分析数据</p>

          <div class="batch-import-container">
            <!-- 数据目录设置 -->
            <div class="content-card" style="margin-bottom: 20px;">
              <h4><i class="fas fa-folder"></i> 数据目录设置</h4>
              <div class="form-group">
                <label class="form-label">数据文件目录</label>
                <input type="text" v-model="dataDirectory" class="form-control" placeholder="请输入数据文件存放目录路径">
                <div class="form-help">
                  <i class="fas fa-info-circle"></i>
                  例如: ./data 或 C:\data
                </div>
              </div>
              <button @click="refreshFileList" class="btn btn-primary" :disabled="!dataDirectory || loading">
                <i v-if="loading" class="fas fa-spinner fa-spin"></i>
                <i v-else class="fas fa-sync-alt"></i>
                {{ loading ? '加载中...' : '刷新文件列表' }}
              </button>
            </div>

            <!-- 导入选项 -->
            <div class="import-options">
              <!-- 快照导入 -->
              <div class="import-card hsnapshot" 
                   :class="{ disabled: importing || !dataDirectory }">
                <div class="import-icon">
                  <i class="fas fa-chart-line"></i>
                </div>
                <div class="import-title">快照导入</div>
                <div class="import-description">导入股票快照数据 (hsnapshot)</div>
                <div class="file-count" v-if="hsnapshotFiles.length > 0">
                  找到 {{ hsnapshotFiles.length }} 个快照文件
                </div>
                <div class="file-count" v-else>
                  未找到快照文件
                </div>
                <button @click="startHsnapshotImport" 
                        class="btn btn-primary import-button"
                        :disabled="importing || !dataDirectory || hsnapshotFiles.length === 0">
                  <i class="fas fa-play"></i> 开始快照导入
                </button>
              </div>

              <!-- 涨停分析导入 -->
              <div class="import-card fboard" 
                   :class="{ disabled: importing || !dataDirectory }">
                <div class="import-icon">
                  <i class="fas fa-trophy"></i>
                </div>
                <div class="import-title">涨停分析导入</div>
                <div class="import-description">导入涨停分析数据 (fboard)</div>
                <div class="file-count" v-if="fboardFiles.length > 0">
                  找到 {{ fboardFiles.length }} 个涨停分析文件
                </div>
                <div class="file-count" v-else>
                  未找到涨停分析文件
                </div>
                <button @click="startFboardImport" 
                        class="btn btn-primary import-button"
                        :disabled="importing || !dataDirectory || fboardFiles.length === 0">
                  <i class="fas fa-play"></i> 开始涨停分析导入
                </button>
              </div>
            </div>

            <!-- 导入进度 -->
            <div v-if="importing || importResults.length > 0" class="progress-container">
              <div class="progress-header">
                <div class="progress-title">导入进度</div>
                <div class="progress-status" 
                     :class="{
                       'importing': importing,
                       'completed': !importing && importResults.length > 0,
                       'error': importError
                     }">
                  {{ importing ? '导入中...' : importError ? '导入失败' : '导入完成' }}
                </div>
              </div>

              <div v-if="importing" class="progress-bar">
                <div class="progress-fill" :style="{ width: progressPercent + '%' }"></div>
              </div>

              <div v-if="importing" class="progress-details">
                <div class="current-file">{{ currentFileName }}</div>
                <div class="progress-text">{{ currentFileIndex + 1 }} / {{ totalFiles }}</div>
              </div>

              <!-- 导入结果 -->
              <div v-if="importResults.length > 0" class="import-results">
                <h5>导入结果</h5>
                <div v-for="result in importResults" :key="result.filename" class="result-item">
                  <div class="result-file">{{ result.filename }}</div>
                  <div class="result-status" :class="'result-status-' + result.status">
                    {{ result.status === 'success' ? '成功' : 
                       result.status === 'error' ? '失败' : '警告' }}
                  </div>
                  <div v-if="result.import_count" class="result-count">
                    {{ result.import_count }} 条记录
                  </div>
                </div>
              </div>

              <!-- 统计摘要 -->
              <div v-if="importSummary" class="summary-stats">
                <div class="stat-item stat-total">
                  <div class="stat-value">{{ importSummary.total }}</div>
                  <div class="stat-label">总文件数</div>
                </div>
                <div class="stat-item stat-success">
                  <div class="stat-value">{{ importSummary.success }}</div>
                  <div class="stat-label">成功导入</div>
                </div>
                <div class="stat-item stat-error">
                  <div class="stat-value">{{ importSummary.error }}</div>
                  <div class="stat-label">导入失败</div>
                </div>
                <div class="stat-item stat-warning">
                  <div class="stat-value">{{ importSummary.warning }}</div>
                  <div class="stat-label">警告</div>
                </div>
                <div class="stat-item stat-total">
                  <div class="stat-value">{{ importSummary.totalRecords }}</div>
                  <div class="stat-label">总记录数</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
    
    <script src="/static/admin/components/sidebar.js"></script>
    <script>
        const { createApp } = Vue;
        
        createApp({
            data() {
                return {
                    dataDirectory: './data',
                    loading: false,
                    importing: false,
                    importError: false,
                    currentFileIndex: 0,
                    totalFiles: 0,
                    currentFileName: '',
                    progressPercent: 0,
                    allFiles: [],
                    importResults: [],
                    importSummary: null
                }
            },
            
            computed: {
                hsnapshotFiles() {
                    return this.allFiles.filter(file => 
                        file.name.toLowerCase().indexOf('hsnapshot') !== -1
                    );
                },
                
                fboardFiles() {
                    return this.allFiles.filter(file => 
                        file.name.toLowerCase().indexOf('fboard') !== -1
                    );
                }
            },
            
            async mounted() {
                // 尝试从localStorage恢复上次使用的目录
                const savedDir = localStorage.getItem('dataDirectory');
                if (savedDir) {
                    this.dataDirectory = savedDir;
                }
                
                // 自动加载文件列表
                if (this.dataDirectory) {
                    await this.refreshFileList();
                }
            },
            
            methods: {
                async refreshFileList() {
                    if (!this.dataDirectory) {
                        console.error('请先设置数据文件目录');
                        return;
                    }
                    
                    this.loading = true;
                    try {
                        const response = await axios.get('/api/import/files', {
                            params: { directory: this.dataDirectory }
                        });
                        
                        if (response.data.success) {
                            const rawFiles = response.data.data.files || [];
                            this.allFiles = rawFiles.map(file => ({
                                name: file.name,
                                size: file.size,
                                path: file.path,
                                type: file.type
                            }));
                            
                            // 保存目录到localStorage
                            localStorage.setItem('dataDirectory', this.dataDirectory);
                        } else {
                            console.error('API返回错误:', response.data.error);
                        }
                    } catch (error) {
                        console.error('加载文件列表失败:', error);
                    } finally {
                        this.loading = false;
                    }
                },
                
                async startHsnapshotImport() {
                    await this.startBatchImport('hsnapshot', this.hsnapshotFiles);
                },
                
                async startFboardImport() {
                    await this.startBatchImport('fboard', this.fboardFiles);
                },
                
                async startBatchImport(fileType, files) {
                    if (files.length === 0) {
                        alert(`未找到${fileType === 'hsnapshot' ? '快照' : '涨停分析'}文件`);
                        return;
                    }
                    
                    this.importing = true;
                    this.importError = false;
                    this.currentFileIndex = 0;
                    this.totalFiles = files.length;
                    this.progressPercent = 0;
                    this.importResults = [];
                    this.importSummary = null;
                    
                    const results = {
                        total: files.length,
                        success: 0,
                        error: 0,
                        warning: 0,
                        totalRecords: 0
                    };
                    
                    for (let i = 0; i < files.length; i++) {
                        const file = files[i];
                        this.currentFileIndex = i;
                        this.currentFileName = file.name;
                        this.progressPercent = ((i + 1) / files.length) * 100;
                        
                        try {
                            const response = await axios.post('/api/import/process', {
                                files: [{
                                    name: file.name,
                                    path: file.path,
                                    type: file.type
                                }]
                            });
                            
                            if (response.data.success) {
                                const processedFiles = response.data.data.processed_files;
                                if (processedFiles && processedFiles.length > 0) {
                                    const result = processedFiles[0];
                                    
                                    // 添加到结果列表
                                    this.importResults.push({
                                        filename: file.name,
                                        status: result.status,
                                        import_count: result.import_count || 0,
                                        message: result.message
                                    });
                                    
                                    // 更新统计
                                    if (result.status === 'success') {
                                        results.success++;
                                        if (result.import_count) {
                                            results.totalRecords += result.import_count;
                                        }
                                    } else if (result.status === 'warning') {
                                        results.warning++;
                                        if (result.import_count) {
                                            results.totalRecords += result.import_count;
                                        }
                                    } else {
                                        results.error++;
                                    }
                                } else {
                                    results.error++;
                                    this.importResults.push({
                                        filename: file.name,
                                        status: 'error',
                                        import_count: 0,
                                        message: '导入失败: 没有返回处理结果'
                                    });
                                }
                            } else {
                                results.error++;
                                this.importResults.push({
                                    filename: file.name,
                                    status: 'error',
                                    import_count: 0,
                                    message: response.data.error || '导入失败'
                                });
                            }
                        } catch (error) {
                            console.error(`导入文件 ${file.name} 失败:`, error);
                            results.error++;
                            this.importResults.push({
                                filename: file.name,
                                status: 'error',
                                import_count: 0,
                                message: error.message || '导入失败'
                            });
                        }
                        
                        // 添加延迟，避免请求过于频繁
                        await new Promise(resolve => setTimeout(resolve, 500));
                    }
                    
                    this.importing = false;
                    this.importSummary = results;
                    
                    // 显示完成消息
                    const message = `批量导入完成！成功: ${results.success}, 失败: ${results.error}, 警告: ${results.warning}, 总记录数: ${results.totalRecords}`;
                    alert(message);
                }
            }
        }).mount('#app');
        // 注入公共侧边栏
        injectAdminSidebar('/admin/batchs');
        
        // 退出登录
        async function logout(){
            try{ 
                await fetch('/admin/logout', {method:'POST'}); 
                location.href='/admin/login'; 
            }catch(e){ 
                location.href='/admin/login'; 
            }
        }
    </script>
</body>
</html>
